package com.cyzy.homework.controller;

import com.cyzy.homework.common.Result;
import com.cyzy.homework.dto.HomeworkFileDTO;
import com.cyzy.homework.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 文件控制器
 */
@RestController
@RequestMapping("/api/files")
@CrossOrigin(origins = "*")
public class FileController {
    
    @Autowired
    private FileService fileService;
    
    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public Result<HomeworkFileDTO> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam String uploaderId) {
        try {
            HomeworkFileDTO result = fileService.uploadFile(file, uploaderId);
            return Result.success("文件上传成功", result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 批量上传文件
     */
    @PostMapping("/upload/batch")
    public Result<List<HomeworkFileDTO>> uploadFiles(
            @RequestParam("files") List<MultipartFile> files,
            @RequestParam String uploaderId) {
        try {
            List<HomeworkFileDTO> result = fileService.uploadFiles(files, uploaderId);
            return Result.success("文件批量上传成功", result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除文件
     */
    @DeleteMapping("/{fileId}")
    public Result<Void> deleteFile(@PathVariable Long fileId) {
        try {
            fileService.deleteFile(fileId);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据ID获取文件信息
     */
    @GetMapping("/{fileId}")
    public Result<HomeworkFileDTO> getFileById(@PathVariable Long fileId) {
        try {
            HomeworkFileDTO result = fileService.getFileById(fileId);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据作业提交ID获取文件列表 - 供老师查看学生提交的文件
     */
    @GetMapping("/submit/{submitId}")
    public Result<List<HomeworkFileDTO>> getFilesBySubmitId(@PathVariable Long submitId) {
        try {
            List<HomeworkFileDTO> result = fileService.getFilesBySubmitId(submitId);
            return Result.success("获取文件列表成功", result);
        } catch (Exception e) {
            return Result.error("获取文件列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量获取文件下载链接 - 供老师端批量下载
     */
    @PostMapping("/batch-download-urls")
    public Result<List<String>> getBatchDownloadUrls(@RequestBody List<Long> fileIds) {
        try {
            List<String> downloadUrls = new ArrayList<>();
            for (Long fileId : fileIds) {
                String downloadUrl = fileService.getFileDownloadUrl(fileId);
                downloadUrls.add(downloadUrl);
            }
            return Result.success("获取批量下载链接成功", downloadUrls);
        } catch (Exception e) {
            return Result.error("获取批量下载链接失败: " + e.getMessage());
        }
    }
    
    /**
     * 下载文件 - 重定向到MinIO预签名URL
     */
    @GetMapping("/download/{fileId}")
    public ResponseEntity<?> downloadFile(@PathVariable Long fileId) {
        try {
            HomeworkFileDTO fileInfo = fileService.getFileById(fileId);
            String downloadUrl = fileService.getFileDownloadUrl(fileId);
            
            // 方案1: 重定向到MinIO预签名URL (推荐)
            return ResponseEntity.status(HttpStatus.FOUND)
                    .location(java.net.URI.create(downloadUrl))
                    .build();
                    
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 获取文件下载链接 - 供老师端直接使用
     */
    @GetMapping("/download-url/{fileId}")
    public Result<String> getDownloadUrl(@PathVariable Long fileId) {
        try {
            String downloadUrl = fileService.getFileDownloadUrl(fileId);
            return Result.success("获取下载链接成功", downloadUrl);
        } catch (Exception e) {
            return Result.error("获取下载链接失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取文件下载URL
     */
    @GetMapping("/{fileId}/download-url")
    public Result<String> getFileDownloadUrl(@PathVariable Long fileId) {
        try {
            String result = fileService.getFileDownloadUrl(fileId);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 验证文件类型
     */
    @GetMapping("/validate/type")
    public Result<Boolean> validateFileType(@RequestParam String fileName) {
        try {
            boolean result = fileService.isValidFileType(fileName);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 验证文件大小
     */
    @GetMapping("/validate/size")
    public Result<Boolean> validateFileSize(@RequestParam long fileSize) {
        try {
            boolean result = fileService.isValidFileSize(fileSize);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 格式化文件大小
     */
    @GetMapping("/format/size")
    public Result<String> formatFileSize(@RequestParam long fileSize) {
        try {
            String result = fileService.formatFileSize(fileSize);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
